<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>敏感词管理 - 敏感词检测系统</title>
    <link th:href="@{/static/css/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/static/css/style.css}" rel="stylesheet">
    <style>
        /* Toast提示样式 */
        .toast-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
        }
        
        .toast {
            background-color: #28a745;
            color: white;
            border-radius: 4px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            padding: 12px 24px;
            margin-bottom: 10px;
            display: none;
            animation: slideIn 0.3s ease-in-out;
            font-size: 14px;
            min-width: 200px;
            text-align: center;
        }
        
        .toast.show {
            display: block;
        }
        
        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
        
        @keyframes fadeOut {
            from {
                opacity: 1;
            }
            to {
                opacity: 0;
            }
        }

        .popover-detail-link {
            color: #218838 !important; /* 深绿色 */
            font-style: italic;
            text-decoration: underline;
            font-size: 1em;
            margin-left: 32px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="container mt-4">
        <div class="row justify-content-center">
            <div class="col-md-8 custom-col-width">
                <!-- Page Title and Back Button -->
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h3 class="mb-0">敏感词管理</h3>
                    <div> <!-- Container for buttons on the right -->
                        <a href="/detector/" class="btn btn-secondary me-2">返回首页</a> <!-- Added me-2 for spacing -->
                        <form action="/detector/logout" method="post" class="d-inline-block"> <!-- Form for logout -->
                            <button type="submit" class="btn btn-danger">退出登录</button> <!-- Logout button -->
                        </form>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <!-- 添加敏感词和批量导入文件选择 -->
                        <div class="row align-items-center">
                            <div class="col-md-3">
                                <label for="wordInput" class="col-form-label">添加敏感词</label>
                            </div>
                            <div class="col-md-6">
                                <input type="text" class="form-control" id="wordInput" placeholder="输入敏感词">
                            </div>
                            <div class="col-md-3 text-end d-flex align-items-center justify-content-end"> <!-- 使用 flex 布局辅助对齐 -->
                                <button class="btn btn-primary me-2" onclick="addWord()" style="width: 80px;">添加</button> <!-- 添加按钮，固定宽度和右边距 -->
                                <input type="file" id="importFile" style="display: none;"> <!-- 隐藏文件选择 -->
                                <button class="btn btn-primary" onclick="document.getElementById('importFile').click()">批量导入</button> <!-- 合并后的导入按钮 -->
                            </div>
                        </div>
                        <!-- 导入结果显示区域 -->
                        <div id="importResult" class="alert mt-3" style="display: none;"></div>
                    </div>
                    <div class="card-body">
                        <!-- 列表头部：标题、总数、搜索、批量删除、导出 -->
                        <div class="row align-items-center mb-3">
                            <div class="col-md-4">
                                <h5 class="mb-0 me-2 d-inline-block">敏感词列表</h5>
                                <span id="totalWordsCount" class="me-3">总数: 20个</span>
                            </div>
                            <div class="col-md-5">
                                <input type="text" class="form-control" id="searchInput" placeholder="搜索敏感词">
                            </div>
                            <div class="col-md-3 text-end"> <!-- 保持右对齐 -->
                                <button class="btn btn-warning me-2" id="batchDeleteBtn">批量删除</button> <!-- 批量删除按钮，橙色 -->
                                <button class="btn btn-success" onclick="exportWords()">导出</button>
                            </div>
                        </div>
                        
                        <!-- 敏感词表格 -->
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>敏感词</th> <!-- 敏感词列头部 -->
                                        <th style="width: 80px;">操作</th> <!-- 操作列头部，宽度固定 -->
                                    </tr>
                                </thead>
                                <tbody id="wordsTableBody">
                                    <!-- 数据由 JavaScript 动态加载 -->
                                </tbody>
                            </table>
                        </div>
                        
                        <!-- 分页 -->
                        <nav>
                            <ul class="pagination justify-content-center" id="pagination">
                                <!-- 分页由 JavaScript 动态加载 -->
                            </ul>
                        </nav>
                    </div>
                </div>

                <!-- 缓存清理设置 -->
                <div class="card mt-4">
                    <div class="card-header">
                        <h5 class="mb-0">缓存清理设置</h5>
                    </div>
                    <div class="card-body">
                         <div class="row align-items-center">
                            <div class="col-md-6">
                                <div class="form-check form-check-inline">
                                  <input class="form-check-input" type="radio" name="cleanPeriod" id="hourlyClean" value="1" checked>
                                  <label class="form-check-label" for="hourlyClean">每小时清理</label>
                                </div>
                                <div class="form-check form-check-inline">
                                  <input class="form-check-input" type="radio" name="cleanPeriod" id="dailyClean" value="24">
                                  <label class="form-check-label" for="dailyClean">每天清理</label>
                                </div>
                            </div>
                            <div class="col-md-6 text-end">
                                <button class="btn btn-danger" onclick="cleanCache()">立即清理</button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 账号设置 -->
                 <div class="card mt-4">
                    <div class="card-header">
                        <h5 class="mb-0">账号设置</h5>
                    </div>
                    <div class="card-body">
                         <div class="row g-3 align-items-center">
                            <div class="col-md-6">
                                <label for="adminUsername" class="col-form-label">用户名</label>
                                <input type="text" id="adminUsername" class="form-control" value="admin">
                            </div>
                            <div class="col-md-6">
                                 <label for="adminPassword" class="col-form-label">密码</label>
                                <input type="password" id="adminPassword" class="form-control" placeholder="输入新密码">
                            </div>
                             <div class="col-12">
                                <button class="btn btn-primary" onclick="updateAccount()">更新账号</button>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>

    <!-- 添加Toast容器 -->
    <div class="toast-container">
        <div class="toast" id="toast"></div>
    </div>

    <script th:src="@{/static/js/jquery-3.6.0.min.js}"></script>
    <script th:src="@{/static/js/bootstrap.bundle.min.js}"></script>
    <script>
        // 全局变量
        let currentPage = 1;
        const pageSize = 10; // 每页显示10条数据
        let selectedWords = new Set(); // 存储所有选中的敏感词

        // 页面加载完成后执行
        $(document).ready(function() {
            // 初始化导入功能事件监听
            $('#importFile').on('change', function() {
                if ($(this).val()) {
                    handleImport(); // 文件选择后直接开始导入
                }
            });

            $('#batchDeleteBtn').on('click', batchDeleteWords); // 绑定批量删除按钮点击事件

            $('#selectAll').off('change').on('change', function() {
                handleSelectAllChange($(this).is(':checked'));
            });

            // 绑定单选框change事件
            $('input[name="cleanPeriod"]').on('change', function() {
                const period = $(this).val();
                const message = period === '1' ? '已切换为每小时清理模式' : '已切换为每天清理模式';
                alert(message);
            });

            // 绑定搜索输入框事件
            $('#searchInput').on('input', function() {
                loadWords(1); // 搜索时从第一页开始加载
            });

            loadWords(1); // 页面加载时加载第一页数据
        });

        // 加载敏感词列表
        function loadWords(page) {
            currentPage = page;
            const searchWord = $('#searchInput').val();
            $.ajax({
                url: '/detector/admin/words/listData',
                type: 'GET',
                data: {
                    page: page,
                    size: pageSize,
                    search: searchWord
                },
                success: function(response) {
                    const words = response.content;
                    const totalElements = response.totalElements;
                    const totalPages = response.totalPages;

                    // 更新总数显示
                    $('#totalWordsCount').text(`总数: ${totalElements}个`);

                    // 渲染表格数据
                    let html = '';
                    words.forEach(sensitiveWord => {
                        // 检查当前词是否在选中集合中
                        const isChecked = selectedWords.has(sensitiveWord.word);
                        html += `
                            <tr>
                                <td>
                                    <input type="checkbox" class="word-checkbox" value="${sensitiveWord.word}" ${isChecked ? 'checked' : ''} style="margin-right: 5px;"> <!-- 添加每行的复选框 -->
                                    ${sensitiveWord.word}
                                </td>
                                <td class="text-end" style="width: 80px;">
                                    <button class="btn btn-danger btn-sm" onclick="deleteWord('${sensitiveWord.word}')">删除</button>
                                </td>
                            </tr>
                        `;
                    });
                    $('#wordsTableBody').html(html);

                    // 更新分页
                    updatePagination(page, totalPages);

                    // 初始化复选框事件监听
                    $('.word-checkbox').off('change').on('change', function() {
                        handleCheckboxChange($(this).val(), $(this).is(':checked'));
                    });
                    // 确保全选框状态与当前页的复选框状态一致
                    updateSelectAllCheckbox();
                }
            });
        }

        // 处理单个复选框变化
        function handleCheckboxChange(word, isChecked) {
            if (isChecked) {
                selectedWords.add(word);
            } else {
                selectedWords.delete(word);
            }
            updateSelectAllCheckbox(); // 单个复选框变化也会影响全选状态
        }

        // 处理全选复选框变化
        function handleSelectAllChange(isChecked) {
            $('.word-checkbox').prop('checked', isChecked);
            $('.word-checkbox').each(function() {
                const word = $(this).val();
                if (isChecked) {
                    selectedWords.add(word);
                } else {
                    selectedWords.delete(word);
                }
            });
            updateSelectAllCheckbox(); // 全选复选框变化后更新自身状态（虽然听起来奇怪，但必要）
        }

        // 更新全选复选框状态
        function updateSelectAllCheckbox() {
            const totalCheckboxes = $('.word-checkbox').length;
            const checkedCheckboxes = $('.word-checkbox:checked').length;
            // 如果当前页有复选框且所有复选框都被选中，则全选框选中
            $('#selectAll').prop('checked', totalCheckboxes > 0 && totalCheckboxes === checkedCheckboxes);
        }

        // 批量删除敏感词
        function batchDeleteWords() {
            if (selectedWords.size === 0) {
                alert('请选择要删除的敏感词'); // 未勾选时提示
                return;
            }

            if (!confirm(`确定要删除选中的 ${selectedWords.size} 个敏感词吗？`)) {
                return;
            }

            const wordsToDelete = Array.from(selectedWords);

            $.ajax({
                url: '/detector/admin/words/batchDelete', // 后端批量删除接口
                type: 'POST', // 或 DELETE，取决于后端设计
                contentType: 'application/json', // 发送 JSON 数据
                data: JSON.stringify(wordsToDelete),
                success: function(response) {
                    if (response === 'success') {
                        alert(`成功删除 ${wordsToDelete.length} 个敏感词`);
                        selectedWords.clear(); // 清空选中集合
                        loadWords(currentPage); // 刷新当前页
                    } else {
                        alert('批量删除失败: ' + response);
                    }
                },
                error: function(xhr, status, error) {
                    alert('批量删除失败: ' + (xhr.responseText || error));
                }
            });
        }

        // 处理文件导入
        function handleImport() {
            const file = $('#importFile')[0].files[0];
            if (!file) {
                return;
            }

            // 检查文件格式
            if (!file.name.toLowerCase().endsWith('.txt')) {
                alert('只支持TXT格式的文件');
                // 重置文件选择状态
                $('#importFile').val('');
                return;
            }

            console.log('开始导入文件:', file.name);
            
            const formData = new FormData();
            formData.append('file', file);

            $.ajax({
                url: '/detector/admin/words/import',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    console.log('导入响应:', response);
                    if (response.error) {
                        $('#importResult')
                            .removeClass('alert-success')
                            .addClass('alert-danger')
                            .text(response.error)
                            .show();
                    } else {
                        let message = `导入完成！成功添加 ${response.addedCount} 个词，重复 ${response.duplicateCount} 个词`;
                        let detailBtn = '';
                        if (response.duplicateCount > 0 && response.duplicateWords && response.duplicateWords.length > 0) {
                            // 构造popover内容，顶部为复制按钮，下方为重复词列表
                            let popoverContent = `<button id='copyDuplicateWordsBtn' class='btn btn-sm btn-outline-success mb-2' style='width:100%;font-size:0.95em;'>复制全部</button><div id='duplicateWordsList' style='max-height:200px;overflow:auto;white-space:pre-line;'>${response.duplicateWords.join('<br>')}</div>`;
                            detailBtn = ` <span style="margin-left: 32px;"></span><a tabindex="0" class="popover-detail-link" role="button" id="duplicateDetailBtn" data-bs-toggle="popover" data-bs-trigger="manual" title="重复词明细" data-bs-html="true" data-bs-content="${popoverContent.replace(/"/g, '&quot;')}">查看详情</a>`;
                        }
                        $('#importResult')
                            .removeClass('alert-danger')
                            .addClass('alert-success')
                            .html(message + detailBtn)
                            .show();
                        if (detailBtn) {
                            setTimeout(function() {
                                var popoverTrigger = document.getElementById('duplicateDetailBtn');
                                if (popoverTrigger) {
                                    var popover = new bootstrap.Popover(popoverTrigger, {
                                        html: true,
                                        placement: 'right',
                                        trigger: 'manual',
                                        sanitize: false
                                    });
                                    $(popoverTrigger).on('click', function(e) {
                                        e.stopPropagation();
                                        if ($(popoverTrigger).attr('aria-describedby')) {
                                            $(popoverTrigger).popover('hide');
                                        } else {
                                            $(popoverTrigger).popover('show');
                                            // 绑定复制按钮事件
                                            setTimeout(function() {
                                                const btn = document.getElementById('copyDuplicateWordsBtn');
                                                if (btn) {
                                                    btn.onclick = function() {
                                                        const words = response.duplicateWords.join('\n');
                                                        navigator.clipboard.writeText(words).then(function() {
                                                            showToast('已复制到剪贴板');
                                                        }, function() {
                                                            showToast('复制失败，请手动选择内容复制');
                                                        });
                                                    };
                                                }
                                            }, 100);
                                        }
                                    });
                                    // 只在点击气泡外部时关闭，点击气泡内容不关闭
                                    $(document).on('mousedown.popover', function(e) {
                                        var popoverId = $(popoverTrigger).attr('aria-describedby');
                                        if (popoverId) {
                                            var popoverElem = document.getElementById(popoverId);
                                            if (popoverElem && !popoverElem.contains(e.target) && e.target !== popoverTrigger) {
                                                $(popoverTrigger).popover('hide');
                                            }
                                        }
                                    });
                                }
                            }, 100);
                        }
                        // 重新加载敏感词列表
                        loadWords(currentPage);
                    }
                    // 重置文件选择状态
                    $('#importFile').val('');
                },
                error: function(xhr, status, error) {
                    console.error('导入失败:', error);
                    console.error('状态:', status);
                    console.error('响应:', xhr.responseText);
                    $('#importResult')
                        .removeClass('alert-success')
                        .addClass('alert-danger')
                        .text('导入失败: ' + (xhr.responseJSON?.error || error))
                        .show();
                    // 重置文件选择状态
                    $('#importFile').val('');
                }
            });
        }

        // 更新分页函数 (从旧代码复制)
        function updatePagination(currentPage, totalPages) {
            let paginationHtml = '';
            const maxPagesToShow = 5;

            // Previous button
            paginationHtml += `<li class="page-item ${currentPage === 1 ? 'disabled' : ''}"><a class="page-link" href="#" onclick="loadWords(${currentPage - 1})">上一页</a></li>`;

            // Page numbers
            let startPage = Math.max(1, currentPage - Math.floor(maxPagesToShow / 2));
            let endPage = Math.min(totalPages, startPage + maxPagesToShow - 1);

            if (endPage - startPage + 1 < maxPagesToShow) {
                startPage = Math.max(1, endPage - maxPagesToShow + 1);
            }

            for (let i = startPage; i <= endPage; i++) {
                paginationHtml += `<li class="page-item ${i === currentPage ? 'active' : ''}"><a class="page-link" href="#" onclick="loadWords(${i})">${i}</a></li>`;
            }

            // Next button
            paginationHtml += `<li class="page-item ${currentPage === totalPages ? 'disabled' : ''}"><a class="page-link" href="#" onclick="loadWords(${currentPage + 1})">下一页</a></li>`;

            $('#pagination').html(paginationHtml);
        }

        // 单条删除敏感词函数 (从旧代码复制)
        function deleteWord(word) {
            if (!confirm('确定要删除敏感词 \'' + word + '\' 吗？')) {
                return;
            }

            $.ajax({
                url: '/detector/admin/words',
                type: 'DELETE',
                data: { word: word },
                success: function(response) {
                    if (response === 'success') {
                        // 从选中集合中移除被删除的词
                        selectedWords.delete(word);
                        loadWords(currentPage); // 删除后重新加载当前页
                    } else {
                        alert(response);
                    }
                },
                error: function(xhr, status, error) {
                    alert('删除失败: ' + (xhr.responseText || error));
                }
            });
        }

        // 添加敏感词函数 (从旧代码复制)
        function addWord() {
            const word = $('#wordInput').val().trim();
            if (!word) {
                alert('请输入敏感词');
                return;
            }

            $.ajax({
                url: '/detector/admin/words',
                type: 'POST',
                data: { word: word },
                success: function(response) {
                    if (response === 'success') {
                        $('#wordInput').val('');
                        // 新添加的词不会被选中，所以无需添加到 selectedWords
                        loadWords(1); // 添加成功后刷新第一页
                    } else {
                        alert(response);
                    }
                },
                error: function(xhr, status, error) {
                    alert('添加失败: ' + xhr.responseText);
                }
            });
        }

        // 搜索敏感词函数 (从旧代码复制)
        function searchWords() {
            // 搜索时清空选中集合，因为搜索结果可能不包含之前选中的词
            selectedWords.clear();
            loadWords(1); // 搜索时加载第一页
        }

        // 导出敏感词函数 (从旧代码复制)
        function exportWords() {
            // 导出功能目前仍是模拟实现，如需真实导出，请调用后端 /detector/admin/words/export 接口
            // 例如: window.location.href = '/detector/admin/words/export';
             $.ajax({
                url: '/detector/admin/words/export',
                type: 'GET',
                xhrFields: {
                    responseType: 'blob'
                },
                success: function(blob) {
                    // 创建下载链接
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = 'sensitive-words.txt';
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                },
                error: function(xhr, status, error) {
                    alert('导出失败: ' + (xhr.responseText || error));
                }
            });
        }

        // 缓存管理相关函数
        function cleanCache() {
            if (!confirm('确定要立即清理缓存吗？')) {
                return;
            }
           
            $.ajax({
                url: '/detector/admin/cache/clean',
                type: 'POST',
                success: function(response) {
                    if (response === 'success') {
                        alert('缓存已清理');
                    } else {
                        alert('清理失败：' + response);
                    }
                },
                 error: function(xhr, status, error) {
                    alert('清理失败，请稍后重试: ' + xhr.responseText);
                }
            });
        }

        // Placeholder for Account Update function (backend not implemented yet)
        function updateAccount() {
            const username = $('#adminUsername').val().trim();
            const password = $('#adminPassword').val().trim();
            
            if (!username || !password) {
                alert('用户名和密码都不能为空');
                return;
            }
            
            if (password.length > 20) {
                alert('密码长度不能超过20位');
                return;
            }
            
            if (!/^[a-zA-Z0-9_]+$/.test(password)) {
                alert('密码只能包含字母、数字和下划线');
                return;
            }
            
            if (!confirm('确定要更新账户信息吗？更新后需要使用新的账户信息重新登录。')) {
                return;
            }
            
            $.ajax({
                url: '/detector/admin/account/update',
                type: 'POST',
                data: {
                    username: username,
                    password: password
                },
                success: function(response) {
                    if (response === 'success') {
                        alert('账户信息已更新，请重新登录');
                        // 退出登录
                        window.location.href = '/detector/logout';
                    } else {
                        alert('更新失败: ' + response);
                    }
                },
                error: function(xhr, status, error) {
                    alert('更新失败: ' + (xhr.responseText || error));
                }
            });
        }

        // 显示Toast提示
        function showToast(message) {
            const toast = document.getElementById('toast');
            toast.textContent = message;
            toast.classList.add('show');
            
            // 3秒后自动消失
            setTimeout(() => {
                toast.style.animation = 'fadeOut 0.3s ease-in-out';
                setTimeout(() => {
                    toast.classList.remove('show');
                    toast.style.animation = '';
                }, 300);
            }, 3000);
        }
    </script>
</body>
</html> 